package com.noble.glamour.ui.qiniu.record;

import android.content.DialogInterface;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.noble.glamour.R;
import com.noble.glamour.module.util.UIShow;
import com.noble.glamour.ui.agora.util.RtcTimerUtil;
import com.noble.library.base.BaseAppCompatActivity;
import com.noble.library.log.PToast;
import com.noble.library.utils.ScreenUtils;
import com.qiniu.pili.droid.shortvideo.PLErrorCode;
import com.qiniu.pili.droid.shortvideo.PLFocusListener;
import com.qiniu.pili.droid.shortvideo.PLRecordStateListener;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.qiniu.shortvideo.record.PLRecordMgr;
import com.qiniu.shortvideo.utils.PLUtils;
import com.qiniu.shortvideo.view.CustomProgressDialog;
import com.qiniu.shortvideo.view.FocusIndicator;
import com.qiniu.shortvideo.view.SectionProgressBar;

/**
 * 短视频录制页
 * Created by Su on 2017/11/10.
 */
public class PLRecordActivity extends BaseAppCompatActivity implements PLRecordStateListener, PLVideoSaveListener, PLFocusListener {

    private GestureDetector mGestureDetector;// 手势聚焦
    private int mFocusIndicatorX;
    private int mFocusIndicatorY;

    private GLSurfaceView preview;          // 拍摄时预览窗口
    private FocusIndicator mFocusIndicator; // 拍摄聚焦
    private ImageView mSwitchCameraBtn;     // 切换前后摄像头
    private ImageView mSwitchFlashBtn;      // 开关闪光灯
    private SeekBar mAdjustBrightnessSeekBar;// 亮度调整进度条
    private SectionProgressBar mSectionProgressBar;// 拍摄进度条
    private CustomProgressDialog mProcessingDialog;// 视频拍摄完成处理中弹框
    private View mRecordBtn;                 // 断点拍摄
    private Chronometer timeView;            // 时间view
    private long recordTime;                 // 计时时间

    private boolean mFlashEnabled;          // 闪光灯开关状态
    private boolean mIsRecording = false;   // 是否处于录制状态

    private PLShortVideoRecorder mShortVideoRecorder;   // 创建录制对象

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pl_short_record);

        mSectionProgressBar = (SectionProgressBar) findViewById(R.id.record_progressbar);
        preview = (GLSurfaceView) findViewById(R.id.preview);
        mRecordBtn = findViewById(R.id.record);
        mSwitchCameraBtn = (ImageView) findViewById(R.id.switch_camera);
        mSwitchFlashBtn = (ImageView) findViewById(R.id.switch_flash);
        mFocusIndicator = (FocusIndicator) findViewById(R.id.focus_indicator);
        mAdjustBrightnessSeekBar = (SeekBar) findViewById(R.id.adjust_brightness);

        // 创建录制对象
        mShortVideoRecorder = PLRecordMgr.getInstance().getShortVideoRecorder(this, preview);
        mShortVideoRecorder.setRecordStateListener(this);
        mShortVideoRecorder.setFocusListener(this);

        mSectionProgressBar.setTotalTime(this, PLRecordMgr.getInstance().getMaxRecordDuration());
        mProcessingDialog = new CustomProgressDialog(this);
        mProcessingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                mShortVideoRecorder.cancelConcat();
            }
        });

        RelativeLayout video_header = (RelativeLayout) findViewById(R.id.video_header);
        video_header.setPadding(0, ScreenUtils.getStatusBarHeight(this), 0, 0);
        timeView = (Chronometer) findViewById(R.id.record_time);

        recordBreak();
        gestureDetector();
    }

    /**
     * 断点拍摄
     */
    private void recordBreak() {
        mRecordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mIsRecording) {
                    mShortVideoRecorder.beginSection();     // 开始一段视频
                    reStart();
                    updateView(true);
                    mIsRecording = true;
                    return;
                }

                // 结束录制
                PToast.showShort("本段视频录制结束");
                mShortVideoRecorder.endSection();  //  结束一段视频
                reStop();
                mIsRecording = false;
                updateView(false);
            }
        });
    }

    /**
     * 手势聚焦操作
     */
    private void gestureDetector() {
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                mFocusIndicatorX = (int) e.getX() - mFocusIndicator.getWidth() / 2;
                mFocusIndicatorY = (int) e.getY() - mFocusIndicator.getHeight() / 2;
                mShortVideoRecorder.manualFocus(mFocusIndicator.getWidth(), mFocusIndicator.getHeight(), (int) e.getX(), (int) e.getY());
                return false;
            }
        });
        preview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mGestureDetector.onTouchEvent(motionEvent);
                return true;
            }
        });
    }

    /**
     * 更新布局
     */
    private void updateView(boolean isRecording) {
        mSwitchCameraBtn.setEnabled(!isRecording);
        mRecordBtn.setActivated(isRecording);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRecordBtn.setEnabled(false);
        mShortVideoRecorder.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        updateView(false);
        mShortVideoRecorder.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mShortVideoRecorder.destroy();
        reStop();
    }

    /**
     * 回删视频片段
     */
    public void onClickDelete(View v) {
        if (!mShortVideoRecorder.deleteLastSection()) {
            PToast.showShort("回删视频段失败");
        }
    }

    public void onClickClose(View v) {
        finish();
    }

    public void onClickConcat(View v) {
        mShortVideoRecorder.endSection();  // 停止录制
        reStop();
        mIsRecording = false;
        updateView(false);
        showEditDialog();
    }


    private void reStart() {
        timeView.setBase(SystemClock.elapsedRealtime() - recordTime);
        timeView.start();
    }

    private void reStop() {
        recordTime = RtcTimerUtil.getInstance().getChronometerSeconds(timeView) * 1000;
        timeView.stop();
    }


    /**
     * 切换摄像头
     */
    public void onClickSwitchCamera(View v) {
        mShortVideoRecorder.switchCamera();
        mFocusIndicator.focusCancel();
    }

    /**
     * 开关闪光灯
     */
    public void onClickSwitchFlash(View v) {
        mFlashEnabled = !mFlashEnabled;
        mShortVideoRecorder.setFlashEnabled(mFlashEnabled);
        mSwitchFlashBtn.setActivated(mFlashEnabled);
    }

    @Override
    public void onReady() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSwitchFlashBtn.setVisibility(mShortVideoRecorder.isFlashSupport() ? View.VISIBLE : View.GONE);
                mFlashEnabled = false;
                mSwitchFlashBtn.setActivated(mFlashEnabled);
                mRecordBtn.setEnabled(true);
                // refreshSeekBar();
                // PToast.showShort("可以开始拍摄咯");
            }
        });
    }

    @Override
    public void onError(int code) {
        String mRecordErrorMsg = "配置出错";
        if (code == PLErrorCode.ERROR_SETUP_CAMERA_FAILED) {
            mRecordErrorMsg = "摄像头配置错误";
        } else if (code == PLErrorCode.ERROR_SETUP_MICROPHONE_FAILED) {
            mRecordErrorMsg = "麦克风配置错误";
        }
        PToast.showOnUiThread(this, mRecordErrorMsg);
    }

    @Override
    public void onDurationTooShort() {
        PToast.showOnUiThread(this, "该视频段太短了");
    }

    @Override
    public void onRecordStarted() {
        PLUtils.log("record start time: " + System.currentTimeMillis());
        mSectionProgressBar.setCurrentState(SectionProgressBar.State.START);
    }

    @Override
    public void onRecordStopped() {
        PLUtils.log("record stop time: " + System.currentTimeMillis());
        mSectionProgressBar.setCurrentState(SectionProgressBar.State.PAUSE);
    }

    @Override
    public void onSectionIncreased(long incDuration, long totalDuration, int sectionCount) {
        PLUtils.log("section increased incDuration: " + incDuration + " totalDuration: " + totalDuration + " sectionCount: " + sectionCount);
        mSectionProgressBar.addBreakPointTime(totalDuration);
    }

    @Override
    public void onSectionDecreased(long decDuration, long totalDuration, int sectionCount) {
        PLUtils.log("section decreased decDuration: " + decDuration + " totalDuration: " + totalDuration + " sectionCount: " + sectionCount);
        mSectionProgressBar.removeLastBreakPoint();
    }

    @Override
    public void onRecordCompleted() {
        reStop();
        PToast.showOnUiThread(this, "已达到拍摄总时长");
    }

    @Override
    public void onProgressUpdate(float percentage) {
        mProcessingDialog.setProgress((int) (100 * percentage));
    }

    @Override
    public void onSaveVideoFailed(final int errorCode) {
        mProcessingDialog.dismiss();
        PToast.showOnUiThread(this, "拼接视频段失败: " + errorCode);
    }

    @Override
    public void onSaveVideoCanceled() {
        mProcessingDialog.dismiss();
    }

    @Override
    public void onSaveVideoSuccess(final String filePath) {
        PLUtils.log("concat sections success filePath: " + filePath);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProcessingDialog.dismiss();
                // 打开视频编辑页
                UIShow.showPLEditActivity(PLRecordActivity.this, filePath);
                finish();
            }
        });
    }

    /**
     * 调整亮度
     */
    private void refreshSeekBar() {
        final int max = mShortVideoRecorder.getMaxExposureCompensation();
        final int min = mShortVideoRecorder.getMinExposureCompensation();
        boolean brightnessAdjustAvailable = (max != 0 || min != 0);
        findViewById(R.id.brightness_panel).setVisibility(brightnessAdjustAvailable ? View.VISIBLE : View.GONE);
        mAdjustBrightnessSeekBar.setOnSeekBarChangeListener(!brightnessAdjustAvailable ? null : new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (i <= Math.abs(min)) {
                    mShortVideoRecorder.setExposureCompensation(i + min);
                } else {
                    mShortVideoRecorder.setExposureCompensation(i - max);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mAdjustBrightnessSeekBar.setMax(max + Math.abs(min));
        mAdjustBrightnessSeekBar.setProgress(Math.abs(min));
    }

    /**
     * 视频合成进度框
     */
    private void showEditDialog() {
        mProcessingDialog.show();
        mShortVideoRecorder.concatSections(this);  // 合成和保存所有的视频片段
    }

    @Override
    public void onManualFocusStart(boolean result) {
        if (result) {
            PLUtils.log("manual focus begin success");
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFocusIndicator.getLayoutParams();
            lp.leftMargin = mFocusIndicatorX;
            lp.topMargin = mFocusIndicatorY;
            mFocusIndicator.setLayoutParams(lp);
            mFocusIndicator.focus();
        } else {
            mFocusIndicator.focusCancel();
            PLUtils.log("manual focus not supported");
        }
    }

    @Override
    public void onManualFocusStop(boolean result) {
        PLUtils.log("manual focus end result: " + result);
        if (result) {
            mFocusIndicator.focusSuccess();
        } else {
            mFocusIndicator.focusFail();
        }
    }

    @Override
    public void onManualFocusCancel() {
        PLUtils.log("manual focus canceled");
        mFocusIndicator.focusCancel();
    }

    @Override
    public void onAutoFocusStart() {
        PLUtils.log("auto focus start");
    }

    @Override
    public void onAutoFocusStop() {
        PLUtils.log("auto focus stop");
    }
}